#include "preHeader.h"
#include "ClientMgr.h"
#include "GameServerSession.h"

ClientMgr::ClientMgr()
{
}

ClientMgr::~ClientMgr()
{
}

void ClientMgr::AddClient(ClientSession* pSession)
{
	m_ClientInfoMap.emplace(pSession->sn(), pSession);
}

void ClientMgr::RemoveClient(ClientSession* pSession)
{
	m_ClientInfoMap.erase(pSession->sn());
}

ClientSession* ClientMgr::GetClient(uint32 sn) const
{
	auto itr = m_ClientInfoMap.find(sn);
	return itr != m_ClientInfoMap.end() ? itr->second : NULL;
}

void ClientMgr::KickClient(ClientSession* pSession, GErrorCode error)
{
	if (error != CommonSuccess) {
		NetPacket pack(SMSG_KICK, s32(error));
		pSession->PushSendPacket(pack);
	}
	pSession->ShutdownSession();
	m_ClientInfoMap.erase(pSession->sn());
}

void ClientMgr::KillClient(ClientSession* pSession)
{
	pSession->KillSession();
	m_ClientInfoMap.erase(pSession->sn());
}

void ClientMgr::KickAllClient(GErrorCode error)
{
	for (auto itr = m_ClientInfoMap.begin(); itr != m_ClientInfoMap.end();) {
		KickClient(itr++->second, error);
	}
}

void ClientMgr::SendLogoutAccount2GameServer(ClientSession* pSession) const
{
	if (pSession->IsAccountOK() && m_ClientInfoMap.count(pSession->sn()) != 0) {
		NetPacket notify(CGG_ACCOUNT_LOGOUT);
		notify << pSession->getAcctId();
		sGameServerSession.PushSendPacket(notify);
	}
}

void ClientMgr::BroadcastPacket2AllClient(const INetPacket& pck) const
{
	for (const auto& pair : m_ClientInfoMap) {
		auto pSession = pair.second;
		if (pSession->IsCharacterOK()) {
			pSession->PushSendPacket(pck);
		}
	}
}
